package com.example.roomdemo;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * @author: tuyrt7 on 2020/9/4.
 */
@Database(entities = {Student.class}, version = 2, exportSchema = true)
public abstract class MyDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = "my_database";
    private static MyDatabase sDatabase;

    public static synchronized MyDatabase get(Context context) {
        if (sDatabase == null) {
            sDatabase = Room.databaseBuilder(context, MyDatabase.class, DATABASE_NAME)
                    //升级失败后，重新创建表，会清除原有数据
//                    .fallbackToDestructiveMigration()
//                    .addMigrations(MIGRATION_1_2/*,MIGRATION_2_3,MIGRATION_1_3*/)
                    // 从assets/databases 目录下读取 students.db
                    .createFromAsset("databases/students.db")
                    .build();
        }
        return sDatabase;
    }

    public abstract StudentDao studentDao();

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
//            //添加 grade字段
//            database.execSQL("alter table student add column grade INTEGER NOT NULL default 0");

            /**
             * 变更 age 类型String 为 int
             */
            //创建临时表 temp_student
            database.execSQL("create table temp_student (id Integer primary key not null,name text,age Text)");
//            //复制旧表 student 中的数据到临时表 temp_student 中
            database.execSQL("insert into temp_student (id, name, age) select id, name, age from student");
//            //删除旧表
            database.execSQL("drop table student");
//            //修改临时表名为 student
            database.execSQL("alter table temp_student rename to student");
        }
    };

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

        }
    };

    static final Migration MIGRATION_1_3 = new Migration(1, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //执行与升级有关的操作
            database.execSQL("alter table student add column grade INTEGER NOT NULL default 0");
            database.execSQL("alter table student rename to teacher");
        }
    };
}
